const fs = require("fs");
const Koa = require("koa");
const KoaRouter = require("@koa/router");
const jwt = require("jsonwebtoken");

const app = new Koa();
const userRouter = new KoaRouter({ prefix: "/users" });

const privateKey = fs.readFileSync("./keys/private.key");
const publicKey = fs.readFileSync("./keys/public.key");

userRouter.get("/login", (ctx, next) => {
  const payload = { username: "admin", password: "123456" };
  const token = jwt.sign(payload, privateKey, {
    algorithm: "RS256",
    expiresIn: "1h",
  }); // 1小时后过期

  ctx.body = {
    code: 0,
    token,
    message: "登录成功",
  };
});

userRouter.get("/list", (ctx, next) => {
  const authorization = ctx.headers.authorization;
  const token = authorization.replace("Bearer ", "");
  try {
    const result = jwt.verify(token, publicKey, {
      algorithms: ["RS256"],
    });

    ctx.body = {
      code: 0,
      message: "获取用户列表成功",
      data: result,
    };
  } catch (error) {
    ctx.body = {
      code: -1010,
      message: "token无效",
    };
  }
});

app.use(userRouter.routes()).use(userRouter.allowedMethods());

app.listen(8000, () => {
  console.log("server is running on http://localhost:8000");
});
